package com.nananer7.servlet;

import com.nananer7.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegistServlet extends HttpServlet{

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        //得到表单提交的内容
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkpassword = request.getParameter("checkpassword");
        String email = request.getParameter("email");

        String pwd = new UserDao().findPswByUsername(username);

        HttpSession session = request.getSession();


        //判断用户名是否存在
        if(pwd !=null){
            session.setAttribute("registmsg","该用户名已存在");
            request.getRequestDispatcher("/regist.jsp").forward(request, response);
            //判断两次输入的密码是否相等
        }else if(!checkpassword.equals(password)){
            session.setAttribute("registmsg","两次输入密码不一致");
            request.getRequestDispatcher("/regist.jsp").forward(request, response);
        }else{
            boolean bl= new UserDao().addUser(username,password,email);
            if(!bl){
                session.setAttribute("registmsg", "注册失败");
                request.getRequestDispatcher("/regist.jsp").forward(request, response);
            }else{
                session.setAttribute("username",username);
                request.getRequestDispatcher("/index.jsp").forward(request, response);
            }

        }

        //判断email
//        if(!isEmail(email)){
//            session.setAttribute("msg","email格式不正确");
//            request.getRequestDispatcher("/regist.jsp").forward(request, response);
//            return;
//        }

    }

    //判断email是否合法
    public static boolean isEmail(String string) {
        if (string == null)
            return false;
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p;
        Matcher m;
        p = Pattern.compile(regEx1);
        m = p.matcher(string);
        if (m.matches())
            return true;
        else
            return false;
    }
}
